package ru.spbsu.electromenu.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.spbsu.electromenu.model.Dish;
import ru.spbsu.electromenu.model.Table;
import ru.spbsu.electromenu.model.Tag;
import ru.spbsu.electromenu.serialization.SerializationException;
import ru.spbsu.electromenu.service.DishService;
import ru.spbsu.electromenu.service.TableService;
import ru.spbsu.electromenu.service.TagService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * Date: 3/23/11
 * Time: 10:36 AM
 *
 * @author Artem Titov
 */
public class GetMenuServlet extends ClientHttpServlet {
    private Logger logger = LoggerFactory.getLogger(GetMenuServlet.class);

    private DishService dishService;
    private TagService tagService;
    private TableService tableService;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        dishService = getBean("dishService");
        tagService = getBean("tagService");
        tableService = getBean("tableService");
        if (dishService == null || tagService == null || tableService == null) {
            logger.error("Failed to instantiate necessary services");
            isValid = false;
            throw new IllegalStateException("Failed to instantiate necessary services");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (!isValid) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
        PrintWriter out = null;
        try {
            final List<Dish> dishes = dishService.getAll();
            final List<Tag> tags = tagService.getAll();
            final List<Table> tables = tableService.getAll();

            final String responseSource = serializer.serializeMenu(dishes, tags, tables);
            response.setCharacterEncoding("UTF-8");
            out = response.getWriter();
            out.print(responseSource);
        } catch (SerializationException e) {
            logger.error("Failed to serialize menu", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (Exception e) {
            logger.error("Internal fail", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (Throwable t) {
            logger.error("Unexpected fail", t);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
